package org.riahispano.twitterds.services.command;

import java.util.List;

import javax.jms.ConnectionFactory;
import javax.jms.Topic;

import org.apache.log4j.Logger;
import org.riahispano.twitterds.domain.LastMessage;
import org.riahispano.twitterds.domain.Status;
import org.riahispano.twitterds.domain.UpdateTimeLine;
import org.riahispano.twitterds.services.TwitterTimeLineService;
import org.springframework.jms.core.JmsTemplate;

/**
 * @author: ecamacho
 * riahispano 2010
 * Command responsible to actually polling a twitter account looking for
 * new messages.
 */
public class TwitterPollingCommand {

    private static final Logger logger = Logger.getLogger(TwitterPollingCommand.class);

    private LastMessage message;

    private Topic topic;

    private JmsTemplate jmsTemplate;


    private TwitterTimeLineService timeLineService;

    public TwitterPollingCommand(LastMessage message, Topic topic, ConnectionFactory factory,
                                 TwitterTimeLineService timeLineService) {

        this.topic = topic;

        this.jmsTemplate = new JmsTemplate(factory);

        this.timeLineService = timeLineService;

        this.message = message;
    }

    public void execute() {
    	logger.debug("[executing command]");
        new Thread(new PollerRunnable(message, timeLineService, topic, jmsTemplate)).run();

    }

    private static class PollerRunnable implements Runnable {

        private LastMessage message;

        private TwitterTimeLineService timeLineService;

        private JmsTemplate jmsTemplate;

        private Topic topic;

        public PollerRunnable(LastMessage message, TwitterTimeLineService timeLineService, Topic topic,
        						JmsTemplate jmsTemplate ) {
            this.message = message;
            this.timeLineService = timeLineService;
            this.topic = topic;
            this.jmsTemplate = jmsTemplate;
        }

        public void run() {
            long lastMessageId = message.getMessageId();
            long tempId;
            
            if (lastMessageId > 0) {
                while (true) {
                	logger.debug("lastMessageId->" + lastMessageId);
                    List<Status> statuses = timeLineService.getFriendsTimelineSinceId(message.getUser(),
                            message.getPassword(), lastMessageId);

                    if (statuses.size() > 0) {
                        tempId = timeLineService.getLastMessageId(statuses);
                        if( lastMessageId != tempId ) {
                        	sendMessage( message.getUser(), statuses );
                        	lastMessageId = tempId;                        	
                        }
                    }
                    
                    try {
						Thread.sleep( 10 * 1000 );
					} catch (InterruptedException e) {
						
						logger.error(e);
					}

                }
            }
        }

        private void sendMessage(final String user, final List<Status> statuses) {
            
			logger.info( "sending message topic " + user );			
			UpdateTimeLine updateTimeLine = new UpdateTimeLine( user, statuses );
            jmsTemplate.convertAndSend( topic, updateTimeLine );
            logger.info("sended");
        }
    }

}
